<template>
  <div>
    <Search @refresh='onRefresh' @search='onSearch' @deleteAll='deleteAdvAll' nodelete>
      <el-button type="primary" :loading="false" @click="dialogVisible=true">添加广告</el-button>
    </Search>

    <el-table :data="tableData" ref="qtable" border v-loading="loading">

      <el-table-column label="图片" align='center'>
        <template #default="scope">
          <span class="getimg" @click="getimg(scope.row)">点击查看</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="广告类型" align='center' />
      <el-table-column prop="url" label="跳转地址" align='center' />
      <el-table-column label="创建时间" align='center'>
        <template #default="scope">
          {{time(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align='center'>
        <template #default="scope">
          {{time(scope.row.updateTime)}}
        </template>
      </el-table-column>

      <el-table-column label="" align='center'>
        <template #default="scope">
          <div class="button" v-if="scope.row.name!='admin'">
            <i class="el-icon-delete"></i>
            <el-button type="text" @click="onClickDeleteUser(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>

    </el-table>
    <!-- ============================================================================ -->
    <!-- ============================================================================ -->
    <div class="pagination">
      <el-pagination background layout="prev, pager, next" :total="total" :page-size='15' hide-on-single-page @current-change='onCurrentChange'>
      </el-pagination>
    </div>
    <!-- ============================================================================ -->
    <!-- ============================================================================ -->
    <el-dialog title="上传广告" v-model="dialogVisible" width="40%" append-to-body destroy-on-close :close-on-click-modal='false'>
      <el-row>
        <el-col :span="12">
          <el-upload class="upload-demo" drag :action="action" :headers="headers" :data='addadv' :auto-upload="false" ref="upload" :on-success='onSuccess' :before-upload="beforeAvatarUpload">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过 500kb
              </div>
            </template>
          </el-upload>

        </el-col>
        <el-col :span="12">
          <div class="radio">
            <span>广告类型:</span>
            <div>
              <el-radio v-model="radio" label="轮播广告">轮播广告</el-radio>
              <el-radio v-model="radio" label="首页广告">首页广告</el-radio>
              <el-radio v-model="radio" label="消息广告">消息广告</el-radio>
            </div>
            <el-divider></el-divider>
            <span>跳转链接(必须以http或https开头):</span>
            <el-input v-model="url" placeholder="请输入跳转地址"></el-input>
            <el-divider></el-divider>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" size='small'>取 消</el-button>
          <el-button type="primary" @click="onAddAdv" size='small'>上传广告</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ============================================================================ -->
    <!-- ============================================================================ -->
    <el-dialog v-model="getimgVisible" width="30%">
      <div class="imag">
        <el-image :src="imag" lazy style="width: 200px; height: 100px">
          <template #placeholder>
            <div class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </template>
        </el-image>
      </div>
      <div class="radio imaginput">
        <span>跳转地址:</span>
        <el-input v-model="advdata.url" placeholder="请输入内容"></el-input>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="getimgVisible = false" size='small'>取 消</el-button>
          <el-button type="primary" @click="updateAdv" size='small'>修改地址</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script lang='ts'>
import { reactive, ref, toRefs } from "vue";
import { Get, Post } from "@/api";
import Search from "@/components/search/Search.vue";
import { $message, time } from "@/components/element";
export default {
  name: " ",
  components: { Search },
  setup() {
    const data = reactive({
      action: (window as any).wedUrl + "/addAdv",
      imag: "",
      headers: {
        token: localStorage.getItem("token"),
      },
      tableData: [],
      total: 0,
      loading: false,
      dialogVisible: false,
      score: 5,
      joblist: [],
      getimgVisible: false,
      advdata: {
        url: "",
        id: "",
      },
    });

    const getimg = (url: any) => {
      data.imag = (window as any).wedUrl + "/" + url.imgurl;
      data.advdata.url = url.url;
      data.advdata.id = url._id;
      data.getimgVisible = true;
    };

    let pageNo: number = 1;
    const onCurrentChange = async (val: number) => {
      pageNo = val;
      await getAdv(val);
    };

    const qtable = ref();
    const getAdv = async (pageNo = 1) => {
      try {
        data.loading = true;
        const userListResult = await Get({
          url: "getAdv",
          data: {
            pageNo,
            pageSize: 15,
          },
        });
        data.tableData = userListResult.data.data;
        data.total = userListResult.data.total;
        qtable.value.doLayout();
        data.loading = false;
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };
    getAdv();

    /* 删除 */
    const onClickDeleteUser = async (param: { _id: string }) => {
      try {
        const deleteResult = await Post({
          url: "deleteAdv",
          data: {
            id: param._id,
          },
        });
        if (deleteResult.data.code == 200) {
          $message("success", deleteResult.data.message);
          onRefresh();
        }
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    /* 刷新 */
    const onRefresh = async () => {
      await getAdv(pageNo);
    };

    /*修改状态  */
    const updateAdv = async () => {
      try {
        const updateResult = await Post({
          url: "updateAdv",
          data: data.advdata,
        });
        if (updateResult.data.code == 200) {
          data.getimgVisible = false;
          onRefresh();
          $message("success", updateResult.data.message);
        }
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    // =======================================================================

    /* 搜索 */
    const onSearch = async (valeu: string) => {
      try {
        data.loading = true;
        const userListResult = await Get({
          url: "searchAdv",
          data: {
            name: valeu,
          },
        });
        data.tableData = userListResult.data.data;
        data.total = userListResult.data.total;
        qtable.value.doLayout();
        data.loading = false;
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    /* 删除全部 */
    const deleteAdvAll = async () => {
      try {
        const deleteResult = await Post({
          url: "deleteAdvAll",
        });
        if (deleteResult.data.code == 200) {
          $message("success", deleteResult.data.message);
          onRefresh();
        }
      } catch (error) {
        console.log(error);
        if (error.data) {
          $message("error", error.data.message);
        }
      }
    };

    /* 添加 */
    const addadv = reactive({
      url: "",
      radio: "",
    });

    const upload = ref();
    const onAddAdv = async () => {
      if (addadv.radio) {
        upload.value.submit();
      } else {
        $message("error", "请选择广告类型");
      }
    };

    const beforeAvatarUpload = (file: any) => {
      console.log(file);
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!(isJPG || isPNG)) {
        $message("error", "上传头像图片只能是 JPG,PNG 格式!");
      }
      if (!isLt2M) {
        $message("error", "上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt2M;
    };

    const onSuccess = async (response: any, file: any, fileList: any) => {
      if (response.code == 200) {
        data.dialogVisible = false;
        onRefresh();
        $message("success", response.message);
      }
    };

    return {
      ...toRefs(data),
      ...toRefs(addadv),
      addadv,
      upload,
      onClickDeleteUser,
      beforeAvatarUpload,
      onCurrentChange,
      updateAdv,
      deleteAdvAll,
      onAddAdv,
      getimg,
      onSuccess,
      onRefresh,
      onSearch,
      qtable,
      time,
    };
  },
};
</script>
<style lang="less" scoped>
.getimg {
  cursor: pointer;
  color: #409eff;
}
.button,
.el-button--text {
  color: red;
}
.button:hover,
.el-button--text:hover {
  color: red;
}
.pagination {
  margin-top: 20px;
  display: flex;
  position: relative;
  .el-pagination {
    position: absolute;
    right: 0;
  }
}
.box-company {
  width: 60%;
  margin: 0 auto;
  .company {
    margin: 15px 0;
  }
}
.radio {
  // border: 1px solid red;
  padding: 0 25px;
  span {
    margin-bottom: 10px;
    display: block;
  }
}
.imag {
  // margin: 0 auto;
  display: flex;
  justify-content: center;
}
.imaginput {
  width: 50%;
  margin: 10px auto;
}
</style>